package com.guli.gulimall.product.service.impl;

import com.alibaba.nacos.client.utils.StringUtils;
import com.guli.common.utils.R;
import com.guli.gulimall.product.dao.*;
import com.guli.gulimall.product.entity.*;
import com.guli.gulimall.product.feign.FeignSearch;
import com.guli.gulimall.product.feign.FeignSms;
import com.guli.gulimall.product.service.*;
import com.guli.gulimall.product.to.MemberPriceTo;
import com.guli.gulimall.product.to.SkuFullReductionTo;
import com.guli.gulimall.product.to.SkuLadderTo;
import com.guli.gulimall.product.to.SpuBoundsTo;
import com.guli.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuImagesServiceImpl spuImagesService;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoDao skuInfoDao;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private FeignSms feignSms;

    @Autowired
    private FeignSearch feignSearch;

    @Autowired
    private SpuInfoDescDao spuInfoDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addSpuInfo(SpuInfoVo spuInfo) {
        //1.pms_spu_info表 主体数据
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        baseMapper.insert(spuInfoEntity);
        //2.pms_spu_info_desc表 商品介绍图片
        List<String> decript = spuInfo.getDecript();
        if (decript!=null){
            String imgsUrl="";
            for (String s : decript) {
                imgsUrl+=","+s;
            }
            SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
            spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
            spuInfoDescEntity.setDecript(imgsUrl);
            spuInfoDao.insert(spuInfoDescEntity);
        }
        //3.pms_spu_images表 商品实物图片
        List<String> images = spuInfo.getImages();
        if (images!=null){
            List<SpuImagesEntity> spuImages = images.stream().map(item -> {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(item);
                spuImagesEntity.setImgName(item.substring(item.lastIndexOf('/')+1));
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(spuImages);
        }
        //4.sms_spu_bounds表-》优惠券微服务
        //todo
        Bounds bounds = spuInfo.getBounds();
        if (bounds!=null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            BeanUtils.copyProperties(bounds,spuBoundsTo);
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
            feignSms.saveSpuBounds(spuBoundsTo);
        }
        //5.pms_product_attr_value 商品的规格属性
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        if (baseAttrs!=null){
            List<ProductAttrValueEntity> collect = baseAttrs.stream().map(item -> {
                ProductAttrValueEntity attrValue = new ProductAttrValueEntity();
                attrValue.setAttrId(item.getAttrId());
                attrValue.setAttrValue(item.getAttrValues());
                attrValue.setQuickShow(item.getShowDesc());
                attrValue.setSpuId(spuInfoEntity.getId());
                AttrEntity attr = attrDao.selectById(item.getAttrId());
                attrValue.setAttrName(attr.getAttrName());
                attrValue.setSearchType(attr.getSearchType());
                return attrValue;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(collect);
        }
        //skus 类别的添加
        List<Skus> skus = spuInfo.getSkus();
        if (skus!=null){
            //6.pms_sku_info表 添加
            for (Skus sku : skus) {
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                //拿到spu的商品描述
                skuInfoEntity.setSkuDesc(spuInfoEntity.getSpuDescription());
                skuInfoEntity.setCatalogId(spuInfo.getCatalogId());
                //默认照片
                List<Images> skuImages1 = sku.getImages();
                if (skuImages1!=null){
                    Images image = skuImages1.stream().filter(img -> img.getDefaultImg().equals(1)).findFirst().get();
                    skuInfoEntity.setSkuDefaultImg(image.getImgUrl());
                }
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setBrandId(spuInfo.getBrandId());
                skuInfoDao.insert(skuInfoEntity);
                //7.pms_sku_sale_attr_value表 销售属性添加
                List<Attr> attr = sku.getAttr();
                if (attr!=null){
                    List<SkuSaleAttrValueEntity> collect = attr.stream().map(saleAttr -> {
                        SkuSaleAttrValueEntity saleAttrValue = new SkuSaleAttrValueEntity();
                        BeanUtils.copyProperties(saleAttr, saleAttrValue);
                        saleAttrValue.setSkuId(skuInfoEntity.getSkuId());
                        //查询属性表是否快速检索
                        AttrEntity attrEntity = attrDao.selectById(saleAttrValue.getAttrId());
                        saleAttrValue.setSearchType(attrEntity.getSearchType());
                        return saleAttrValue;
                    }).collect(Collectors.toList());
                    skuSaleAttrValueService.saveBatch(collect);
                }
                //8.pms_sku_images表 添加图集
                List<Images> skuImages = sku.getImages();
                if (skuImages!=null){
                    List<SkuImagesEntity> collect = skuImages.stream().filter(img -> StringUtils.isNotEmpty(img.getImgUrl())).map(img -> {
                        SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                        BeanUtils.copyProperties(img, skuImagesEntity);
                        skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                        return skuImagesEntity;
                    }).collect(Collectors.toList());
                    skuImagesService.saveBatch(collect);
                }
                //9.sms_sku_ladder  sku的打折信息
                SkuLadderTo skuLadderTo = new SkuLadderTo();
                skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
                skuLadderTo.setFullCount(sku.getFullCount());
                skuLadderTo.setDiscount(sku.getDiscount());
                skuLadderTo.setAddOther(sku.getCountStatus());
                feignSms.saveskuLadder(skuLadderTo);
                //10.sms_sku_full_reduction sku的满减
                SkuFullReductionTo skuFullReductionTo = new SkuFullReductionTo();
                skuFullReductionTo.setSkuId(skuInfoEntity.getSkuId());
                skuFullReductionTo.setFullPrice(sku.getFullPrice());
                skuFullReductionTo.setReducePrice(sku.getReducePrice());
                skuFullReductionTo.setAddOther(sku.getPriceStatus());
                feignSms.saveSkuFullReduction(skuFullReductionTo);
                //11.sms_member_price表 会员打折
                List<MemberPrice> memberPrice = sku.getMemberPrice();
                if (memberPrice!=null){
                    List<MemberPriceTo> collect = memberPrice.stream().map(item -> {
                        MemberPriceTo memberPriceTo = new MemberPriceTo();
                        memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                        memberPriceTo.setMemberLevelId(item.getId());
                        memberPriceTo.setMemberLevelName(item.getName());
                        memberPriceTo.setMemberPrice(item.getPrice());
                        return memberPriceTo;
                    }).collect(Collectors.toList());
                    feignSms.saveMemberPrice(collect);
                }
            }
        }
    }

    @Override
    public R spuUp(Long spuId) {
        //添加数据到es
        //查询每个上架手机属性
        List<SkuVo> collect = spuInfoDao.findSpuById(spuId).stream().map(item -> {
            //查询规格属型（spu）使用set集合实现 如果spu与sku中的属性有相同的就只要第一个填入的数据不可重复（重写equre和hashequre）
            Set<Attrs> spus = spuInfoDao.findSpById(item.getSpuId());
            //查询销售属型（sku）
            List<Attrs> skus = spuInfoDao.findSkById(item.getSkuId());
            skus.addAll(spus);
            item.setAttrs(skus);
            return item;
        }).collect(Collectors.toList());
        //feign调用
        R r=feignSearch.addAll(collect);
        //修改spu表商品状态为上架
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        spuInfo.setId(spuId);
        spuInfo.setPublishStatus(1);
        baseMapper.updateById(spuInfo);
        return R.ok();
    }
//    SpuInfoEntity spuInfo = baseMapper.selectById(spuId);
//    List<SkuInfoEntity> skuInfos = skuInfoDao.selectList(new QueryWrapper<SkuInfoEntity>().eq("catalog_id", spuInfo.getCatalogId()));
//        if (skuInfos!=null){
//        BulkRequest request = new BulkRequest("product");
//        try {
//            skuInfos.stream().forEach(skuInfo->{
//                SkuVo skuVo = new SkuVo();
//                //查询该商品发布中的规格属性
//                List<SkuVo.Attrs> attrsList=new ArrayList<>();
//                List<ProductAttrValueEntity> attrValue = productAttrValueDao.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId)
//                        .eq("search_type", 1));
//                if (attrValue!=null){
//                    attrsList= attrValue.stream().map(item -> {
//                        SkuVo.Attrs attrs = new SkuVo.Attrs();
//                        attrs.setAttrId(item.getAttrId());
//                        attrs.setAttrName(item.getAttrName());
//                        attrs.setAttrValue(item.getAttrValue());
//                        return attrs;
//                    }).collect(Collectors.toList());
//                }
//                //查询该商品发布中的销售属性
//                List<SkuSaleAttrValueEntity> saleAttr = skuSaleAttrValueDao.selectList(new QueryWrapper<SkuSaleAttrValueEntity>().eq("sku_id", skuInfo.getSkuId())
//                        .eq("search_type", 1));
//                if (saleAttr!=null){
//                    List<SkuVo.Attrs> collect = saleAttr.stream().map(item -> {
//                        SkuVo.Attrs attrs = new SkuVo.Attrs();
//                        attrs.setAttrId(item.getAttrId());
//                        attrs.setAttrName(item.getAttrName());
//                        attrs.setAttrValue(item.getAttrValue());
//                        return attrs;
//                    }).collect(Collectors.toList());
//                    attrsList.addAll(collect);
//                }
//                skuVo.setAttrs(attrsList);
//                BrandEntity brand = brandDao.selectById(spuInfo.getBrandId());
//                skuVo.setBrandId(brand.getBrandId());
//                skuVo.setBrandName(brand.getName());
//                skuVo.setBrandImg(brand.getLogo());
//                skuVo.setCatalogId(spuInfo.getCatalogId());
//                CategoryEntity category = categoryDao.selectById(spuInfo.getCatalogId());
//                skuVo.setCatalogName(category.getName());
//                // todo 查询库存微服务判断是否还有库存
//                skuVo.setHasStock(true);//是否有库存
//                skuVo.setHotScore(0L);//是否有评论
//                skuVo.setSaleCount(skuInfo.getSaleCount());//可能会下架之后返厂所以拿到之前的销售数量
//                skuVo.setSkuId(skuInfo.getSkuId());
//                skuVo.setSkuImg(skuInfo.getSkuDefaultImg());
//                skuVo.setSkuPrice(skuInfo.getPrice());
//                skuVo.setSkuTitle(skuInfo.getSkuTitle());
//                skuVo.setSpuId(spuId);
//                IndexRequest indexRequest = new IndexRequest();
//                indexRequest.id(skuInfo.getSkuId().toString());
//                String jsonString = JSONObject.toJSONString(skuVo);
//                indexRequest.source(jsonString, XContentType.JSON);
//                request.add(indexRequest);
//            });
//            BulkResponse bulkResponse = client.bulk(request, EsConfig.COMMON_OPTIONS);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
}